package com.daocao.hua.fragment;

import android.Manifest;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.hua.R;
import com.daocao.hua.activity.Application;
import com.daocao.hua.activity.MainActivityNew;
import com.daocao.hua.activity.PermissionActivity;
import com.daocao.hua.adapter.RepayRecordNewAdapter;
import com.daocao.hua.constant.Const;
import com.daocao.hua.event.BannerEvent;
import com.daocao.hua.event.OnRepaySuccessEventMsg;
import com.daocao.hua.event.SelectMoneyEvent;
import com.daocao.hua.http.InfoCallBack;
import com.daocao.hua.impl.RepayInfoImpl;
import com.daocao.hua.interfaces.OnRecyclerViewListener;
import com.daocao.hua.model.RepayRecordModel;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.view.CircularProgress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xsooy-pc on 2017/5/3.
 */

public class RepayRecordFragment extends BaseFragment implements View.OnClickListener {
    private RecyclerView recyclerView;
    private RepayRecordNewAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private List<RepayRecordModel.Data> list = new ArrayList<RepayRecordModel.Data>();
    private int lastVisibleItem;
    //    private CircularProgress loading;
    private int pastDuePageIndex;
    private LinearLayout nothing;
    private boolean hasData;
    private TextView loan_now;
    private BannerEvent bannerEvent = new BannerEvent();

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_repay_record;
    }

    @Override
    protected void initView() {
        nothing = findView(R.id.nothing);
//        loading = findView(R.id.progressBar);
        loan_now = findView(R.id.loan_now);
        loan_now.setOnClickListener(this);
        recyclerView = findView(R.id.recycler_view);
//        recyclerView.setHasFixedSize(true);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RepayRecordNewAdapter(getContext());
        recyclerView.setAdapter(adapter);
//        recyclerView.setItemViewCacheSize(5);
        //刷新
        swipeRefreshLayout = findView(R.id.swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(R.color.refresh_color_bule);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                EventBus.getDefault().post(bannerEvent);
                swipeRefreshLayout.setRefreshing(true);
                getRepayRecord(swipeRefreshLayout, Const.PullType.PULL_DOWN, 1);
            }
        });
//        recyclerView.addOnScrollListener(new OnSecLoadeMoreListener(adapter) {
//            @Override
//            public void onLoadMore(int page) {
//                swipeRefreshLayout.setRefreshing(true);
//                getRepayRecord(swipeRefreshLayout, Const.PullType.PULL_UP, page);
//            }
//        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView,
                                             int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == 0) {//停止滚动

                }
                try {
                    if (adapter == null) return;
                    if (newState == RecyclerView.SCROLL_STATE_IDLE
                            && lastVisibleItem + 1 == adapter.getItemCount()) {
                        swipeRefreshLayout.setRefreshing(true);
                        getRepayRecord(swipeRefreshLayout, Const.PullType.PULL_UP, pastDuePageIndex + 1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });


        EventBus.getDefault().register(this);
        setData();
    }

    @Override
    public void onClick(View v) {
        if (PreferenceUtils.getBoolean(getContext(), "is_locat", false)) {
            EventBus.getDefault().post(new SelectMoneyEvent());
        } else {
            checkPermission(new PermissionActivity.CheckPermListener() {
                                @Override
                                public void superPermission() {
                                    PreferenceUtils.putBoolean(Application.getInstance(), "is_locat", true);
                                    ((MainActivityNew) getActivity()).initLocation();
                                }
                            }, R.string.location_p, R.string.get_location,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE);
        }
    }

    public void setData() {
        getRepayRecord(null, Const.PullType.PULL_DOWN, 1);
    }


    /**
     * 还款记录
     */
    private void getRepayRecord(final SwipeRefreshLayout refreshLayout, final int type, final int pageIndex) {
        new RepayInfoImpl().getRepayRecord(getContext(), pageIndex, new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                try {
                    RepayRecordModel model = (RepayRecordModel) o;
                    adapter.add(model.getData(), pageIndex == 1);
                    list = model.getData();
                    if (list.size() <= 0) {
                        if (!hasData)
                            nothing.setVisibility(View.VISIBLE);
                        else
                            ToastUtil.makeText(getActivity(), getResources().getString(R.string.no_more_date_text), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    hasData = true;
                    if (pageIndex > model.getPager().getAllPages()) {
                        ToastUtil.makeText(getActivity(), getResources().getString(R.string.no_more_date_text), Toast.LENGTH_SHORT).show();
                    }
                    pastDuePageIndex = pageIndex;
                    if (nothing.getVisibility() == View.VISIBLE) {
                        nothing.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (refreshLayout != null) refreshLayout.setRefreshing(false);
                }
            }

            @Override
            public void onFailure(String cause) {
                if (refreshLayout != null) refreshLayout.setRefreshing(false);
                if (!TextUtils.isEmpty(cause))
                    ToastUtil.makeText(getContext(), cause, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void repaySucessEventBus(OnRepaySuccessEventMsg msg) {
        getRepayRecord(null, Const.PullType.PULL_DOWN, 1);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
